package controller

import (
	"database/sql"
	"encoding/json"
	"fabric-go-sdk/database"
	"fabric-go-sdk/tools"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type userInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func Login(c *gin.Context) {
	// 获取账号密码
	//username := c.PostForm("username")
	//password := c.PostForm("password")
	info, err := c.GetRawData()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "获取消息失败",
			"success": false,
		})
		return
	}
	userinfo := &userInfo{}
	json.Unmarshal(info, userinfo)
	fmt.Println("login---username", userinfo.Username)
	fmt.Println("login---password", userinfo.Password)
	username := userinfo.Username
	password := userinfo.Password
	//查询mysql检测账号密码是否正确
	u, err := database.QueryByUserName(username)
	if err != nil {
		if err == sql.ErrNoRows {
			c.JSON(http.StatusOK, gin.H{
				"code":    200,
				"message": "账号" + username + "未注册",
				"success": false,
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "数据库查询失败,err:" + err.Error(),
			"success": false,
		})
		return
	}
	if u.Password != password {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "密码错误",
			"success": false,
		})
		return
	}
	// 生成token
	token, err := tools.CreateJwtToken(strconv.Itoa(u.Id), username)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "token生成失败,err:" + err.Error(),
			"success": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "成功",
		"success": true,
		"data": gin.H{
			"token": token,
		},
	})
}

func GetAvatar(c *gin.Context) {
	// 从上下文中获取userid
	userId, ok := c.Get("userid")
	if !ok {
		c.JSON(http.StatusOK, gin.H{
			"mes": "获取userid失败",
		})
		return
	}
	useridsring, ok := userId.(string)
	if !ok {
		c.JSON(http.StatusOK, gin.H{
			"mes": "空接口断言错误",
		})
		return
	}
	userid, _ := strconv.Atoi(useridsring)
	u, err := database.QueryByUserId(userid)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"err": err.Error(),
			"mes": "数据库查询失败",
		})
		return
	}
	c.File(u.AvatarAdress)
	return
}

// 获取用户信息
func GetUserInfo(c *gin.Context) {
	userName, ok := c.Get("username")
	fmt.Println("GetUserInfo---", userName)
	if !ok {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"success": false,
			"message": "无法获取username",
		})
		return
	}
	fmt.Println("GetUserInfo---", userName)
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"success": true,
		"message": "成功",
		"data": gin.H{
			"avatar": "aaa",
			"name":   userName.(string),
		},
	})

}

// 登出
func Logout(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    200,
		"message": "成功",
		"data":    gin.H{},
	})
}
